package com.zretc.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.aliyuncs.exceptions.ClientException;
import com.zretc.entity.User;
import com.zretc.service.UserService;
import com.zretc.service.impl.UserServiceImpl;
import com.zretc.util.SmsDemo;




/**
 * @author 赵坤
 * Servlet implementation class UserServlet
 * 前端用户登录、登出、注册
 */
@WebServlet("/front/UserServlet")
@MultipartConfig
public class FrontUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
	private boolean key;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FrontUserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 *      根据前端页面不同op值判断执行不同操作
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置请求参数的编码格式
		request.setCharacterEncoding("UTF-8");

		// 接收请求中的参数op,请求操作标识
		String op = request.getParameter("op");

		if (op == null) {
			// 前往登录页面
			response.sendRedirect("login.jsp");
		} else if ("login".equals(op)) {
			doLogin(request, response);
		} else if ("logout".equals(op)) {
			doLogout(request, response);
		} else if ("register".equals(op)) {
			doRegister(request, response);
		} else if("existsOfUserAccount".equals(op)) {
			// 判断账号是否存在
			doExistsOfAccountName(request,response);
	    }else if("existsOfUserPhone".equals(op)) {
			// 判断手机号是否存在
	    	doExistsOfUserPhone(request,response);
	    }else if("existsOfUserName".equals(op)) {
			// 判断用户名是否存在
	    	doExistsOfUserName(request,response);
	    }else if("userPhoneCodeCheck".equals(op)) {
			// 验证验证码
	    	userPhoneCodeCheck(request,response);
	    }else if("phoneCode".equals(op)) {
		   // 发送手机验证码
    
	    	try {
				doPhoneCode(request,response);
			} catch (ClientException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
    }
	}
	
	/**
	 * 验证验证码
	 * @throws IOException 响应错误
	 */
	
	private void userPhoneCodeCheck(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String code = request.getParameter("userPhoneCode");  	
		response.setCharacterEncoding("UTF-8"); 
		System.out.println(request.getSession().getAttribute("userPhoneCode"));
		if(request.getSession().getAttribute("userPhoneCode").equals(code)){
			key = true;
			response.getWriter().write("true");   
		}else {
			response.getWriter().write("false");   
		}
		response.flushBuffer();   

		
	}
	
	/**
	 * 发送验证码
	 * @throws IOException 响应错误
	 */
	

	private void doPhoneCode(HttpServletRequest request, HttpServletResponse response) throws ClientException, IOException {
		String userPhone = request.getParameter("userPhone");
		SmsDemo.sendSms(userPhone,request);
		
		System.out.println(userPhone);
		response.getWriter().write("true");   
		

		
	}

	/**
	 * 判断用户名是否重复
	 * @throws IOException 响应错误
	 */
	
	private void doExistsOfUserName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userName = request.getParameter("userName");
		boolean existsOfUserName = userService.existsOfUserName(userName);
		// 响应数据
		response.getWriter().write(existsOfUserName+"");
		
	}

	/**
	 * 判断账户是否重复
	 * @throws IOException 响应错误
	 */

	private void doExistsOfAccountName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userAccount = request.getParameter("userAccount");
		boolean existsOfUserAccount = userService.existsOfUserAccount(userAccount);
		// 响应数据
		response.getWriter().write(existsOfUserAccount+"");
		
	}
	
	

	/**
	 * 判断手机号是否重复
	 * @throws IOException 响应错误
	 */

	private void doExistsOfUserPhone(HttpServletRequest request, HttpServletResponse response) throws IOException {
		boolean existsOfUserPhone = userService.existsOfUserPhone(request.getParameter("userPhone"));
		// 响应数据
		response.getWriter().write(existsOfUserPhone+"");
		
	}

	/**
	 * 用户登出
	 * @throws IOException 响应错误
	 */

	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		response.sendRedirect("index.jsp");

	}
	
	/**
	 * 用户注册
	 * @throws IOException
	 * @throws ServletException
	 */

	private void doRegister(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		
		
		// 业务逻辑层
		if(key=true) {
		Integer userId = null;
		String userAccount = request.getParameter("userAccount");
		String userName = request.getParameter("userName");
		String userPassword = request.getParameter("userPassword");
		String userPhone = request.getParameter("userPhone");
		// 接收文件组件
		Part part = request.getPart("userPicture");
		// 判断用户是否有上传文件
		if(part.getSize() == 0) { // 没有上传
			// 业务逻辑层
			User user = new User(userId,userAccount,userName,userPassword,null,userPhone);
			userService.insertUser(user);
		}else { // 有上传
			
			// 允许的文件图片类型
			String allowImgType ="image/jpg,image/jpeg,image/png";
			// 允许的文件图片类型集合
			List<String> allowImgTypeList = Arrays.asList(allowImgType.split(","));
			
			// 判断上传的文件类型是否合法
			String contentType = part.getContentType(); // 获取上传文件的MIME类型
			
			// 判断上传的文件MIME类型是否在指定的允许类型集合
			if(allowImgTypeList.contains(contentType)==false) {
				System.out.println("文件类型不匹配!");
				// 重定向注册页面,提示文件不合法
				response.sendRedirect("register.jsp?fileuploaderror=fileuploaderror");
				return;
			}else {
				// 获取文件真实名:Servlet 3.0不提供获取上传文件名的方法,通过请求头信息间接获取
				String header = part.getHeader("content-disposition");
				String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
				// 获取真实文件名的后缀
				String fileSuffix = realName.substring(realName.lastIndexOf("."));
				// 使用时间戳+随机数自动生成文件名,避免文件名重复问题
				// JDK1.8 日期时间类
				LocalDateTime now = LocalDateTime.now();
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyyMMddhhmmssSSS");
				// 将当前日期时间转成字符串
				String formatDate = ofPattern.format(now);	
				// 随机数
				int random = (int) (Math.random()*1000+1);
				// 拼接
				StringBuffer fileName = new StringBuffer();
				fileName.append(formatDate).append(random);
				
				// 将文件存储在指定服务器中(本地电脑D盘)
				File file = new File("D:\\upload\\images");
				
				// 将文件写入指定位置
				String filePath = file.getPath() + File.separator + fileName + fileSuffix; // E:\fileupload\images\1.jpg
				part.write(filePath);
				
				String userPicture = fileName + fileSuffix;
				
				// 调用业务层
				User user = new User(userId,userAccount,userName,userPassword,userPicture,userPhone);
				userService.insertUser(user);
			}
		}
		// 重定向到前台首页
		response.sendRedirect("index.jsp");
		}else {
			response.getWriter().write("验证码错误");
		}

	}
	
	/**
	 * 用户登录
	 * @throws IOException 响应错误
	 */

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 调度器
		// 1.调用业务层逻辑
		String userAccount = request.getParameter("userAccount");
		String userPassword = request.getParameter("userPassword");
		User user = userService.userlogin(userAccount, userPassword);
		if (user != null) {
			// 登录成功
			// 用户信息存储在session会话作用域中
			HttpSession session = request.getSession();
			session.setAttribute("user", user);

			// 获取复选框的值
			String rememberPassword = request.getParameter("rememberPassword");

			// 用户选择记住密码
			if (rememberPassword != null) {
				// 通过Servlet像cookie添加用户信息并发送给HTTP
				Cookie cookie = new Cookie(userAccount, userPassword);
				// 设置cookie有效时间
				cookie.setMaxAge(60 * 5);
				// 将cookie发送给HTTP
				response.addCookie(cookie);
			} else {
				// 用户选择不记住密码，通过Servlet删除Cookie（setMaxAge(0)），读取并存储新Cookie并发送给HTTP
				Cookie[] cookies = request.getCookies();
				Cookie cookie = null;
				for (int i = 0; i < cookies.length; i++) {
					cookie = cookies[i];
					if (cookie.getName().equals(userAccount)) {
						cookie.setMaxAge(0);
						response.addCookie(cookie);
					}
					if (cookie.getValue().equals(userPassword)) {
						cookie.setMaxAge(0);
						response.addCookie(cookie);
					}
				}
			}
			// 重定向到首页
			response.sendRedirect("index.jsp");
		} else {
			// 登录失败
			// 重定向到登录页面
			response.sendRedirect("userSignIn.jsp?loginErrorMessage=error");
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
}
